<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  <!-- 谷歌收录 -->
  <meta name="google-site-verification" content="-5hl8eC4wfapGZhZouwMVUcKG0iaynijVRJbqVlzXm4" />
  
  
  <title>Python虚拟环境 | 鴻塵</title>
  <meta name="description" content="摘要：本文介绍Python中常用虚拟环境的用法。">
<meta property="og:type" content="article">
<meta property="og:title" content="Python虚拟环境">
<meta property="og:url" content="https://hwame.top/20210629/python-virtual-environment.html">
<meta property="og:site_name" content="鴻塵">
<meta property="og:description" content="摘要：本文介绍Python中常用虚拟环境的用法。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://image.iswbm.com/20200209161935.png">
<meta property="og:image" content="https://i.loli.net/2018/06/11/5b1e7d36ce8ad.png">
<meta property="og:image" content="https://i.loli.net/2018/06/11/5b1e7f140be6a.png">
<meta property="og:image" content="https://i.loli.net/2018/06/11/5b1e805c996c8.png">
<meta property="og:image" content="https://i.loli.net/2018/06/11/5b1e812db603f.png">
<meta property="og:image" content="http://image.iswbm.com/20210606214719.png">
<meta property="og:image" content="http://image.iswbm.com/Fk6WZ2xbqg2DM3AvnYCpsiKQ4xOn">
<meta property="og:image" content="http://image.iswbm.com/FjuJ8yZsgjkzVuBRZHxK1ZnnzaEX">
<meta property="og:image" content="http://image.iswbm.com/20190612211330.png">
<meta property="og:image" content="http://image.iswbm.com/20190612213015.png">
<meta property="og:image" content="http://image.iswbm.com/20190612213950.png">
<meta property="og:image" content="http://image.iswbm.com/20190612211925.png">
<meta property="og:image" content="http://image.iswbm.com/20190614000336.png">
<meta property="og:image" content="http://image.iswbm.com/20190612215924.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130124107950.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130124554404.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130125257203.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130131138939.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130210539907.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130215320069.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130220233001.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201130215826513.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201220164337699.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201226172542169.png">
<meta property="og:image" content="http://image.iswbm.com/20201231140727.png">
<meta property="og:image" content="http://image.iswbm.com/image-20201226174305992.png">
<meta property="article:published_time" content="2021-06-28T23:54:48.000Z">
<meta property="article:modified_time" content="2021-07-08T00:04:25.000Z">
<meta property="article:author" content="鴻塵">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://image.iswbm.com/20200209161935.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://hwame.top/20210629/python-virtual-environment.html">
  
    <link rel="alternate" href="true" title="鴻塵" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
    <link href="//cdn.jsdelivr.net/npm/katex@0.9.0/dist/katex.min.css" rel="stylesheet">
  
  
  
    <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css" rel="stylesheet">
  
  
<meta name="generator" content="Hexo 5.4.2"></head>


<script src="https://cdn.jsdelivr.net/gh/bobcn/hexo_resize_image.js@master/hexo_resize_image.js"></script>
<body class="main-center theme-purple" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://hwame.top" target="_blank">
          <img class="img-circle img-rotate" src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">鴻塵</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Pythoner, Data Analyst</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> 湖北-武汉</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/categories">
            
            <i class="icon icon-folder-open"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">资源</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-gallery">
          <a href="/gallery">
            
            <i class="icon icon-delicious"></i>
            
            <span class="menu-title">相册</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-stackexchange"></i>公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎来到鴻塵的博客!<br>鴻塵的<u><a target="_blank" rel="noopener" href="https://weibo.com/hwamei" style="color:#E541E5;">微博</a></u>主页，鴻塵的<u><a target="_blank" rel="noopener" href="https://github.com/hwame" style="color:#E541E5;">Github</a></u>主页，如果我可以忘记的<u><a target="_blank" rel="noopener" href="https://www.zhihu.com/people/hwame" style="color:#E541E5;">知乎</a></u>主页。</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-tags"></i>标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/CentOS/" style="font-size: 13px; color: #fff">CentOS</a> <a href="/tags/Go/" style="font-size: 13.2px; color: #fff">Go</a> <a href="/tags/Hexo/" style="font-size: 13.8px; color: #fff">Hexo</a> <a href="/tags/Linux/" style="font-size: 14px; color: #fff">Linux</a> <a href="/tags/Linux%E9%83%A8%E7%BD%B2/" style="font-size: 13px; color: #fff">Linux部署</a> <a href="/tags/MongoDB/" style="font-size: 13.4px; color: #fff">MongoDB</a> <a href="/tags/Spark/" style="font-size: 13px; color: #fff">Spark</a> <a href="/tags/matplotlib/" style="font-size: 13.2px; color: #fff">matplotlib</a> <a href="/tags/miscellanea/" style="font-size: 13.6px; color: #fff">miscellanea</a> <a href="/tags/python/" style="font-size: 14px; color: #fff">python</a> <a href="/tags/shell/" style="font-size: 13.6px; color: #fff">shell</a> <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/" style="font-size: 13px; color: #fff">大数据</a> <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" style="font-size: 13px; color: #fff">数据结构与算法</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 13px; color: #fff">爬虫</a>
    </div>
  </div>

<script type="text/javascript">
    var everytag=document.getElementsByClassName("widget-body tagcloud")[0].children;
    for (var i = everytag.length - 1; i >= 0; i--) {
    	var r=Math.floor(Math.random()*255);
        var g=Math.floor(Math.random()*255);
        var b=Math.floor(Math.random()*255);
        everytag[i].style.background = "rgb("+r+","+g+","+b+")";
    }
</script>
    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-folder-open"></i>分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Go/">Go</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/MongoDB/">MongoDB</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/miscellanea/">miscellanea</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-archives-fill"></i>归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/">2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/">2021</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/">2020</a><span class="archive-list-count">17</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-shu-fill"></i>最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled ">
        
          <li>
            
            <div class="item-thumb">
              <a href="/20220327/channel-and-goroutine-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言中的通道" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220327/channel-and-goroutine-in-go.html" class="title">Go语言中的通道</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-27T11:06:16.000Z" itemprop="datePublished">2022-03-27</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220323/when-to-use-pointer-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言什么时候使用指针" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220323/when-to-use-pointer-in-go.html" class="title">Go语言什么时候使用指针</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-23T12:49:57.000Z" itemprop="datePublished">2022-03-23</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220228/awesome-images-in-markdown.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="Markdown中图片的高级用法" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20220228/awesome-images-in-markdown.html" class="title">Markdown中图片的高级用法</a>
              </p>
              <p class="item-date">
                <time datetime="2022-02-28T15:27:50.000Z" itemprop="datePublished">2022-02-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220116/shell-regular-expression.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/linux-icon.png)" alt="Shell正则表达式" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Linux/">Linux</a>
              </p>
              <p class="item-title">
                <a href="/20220116/shell-regular-expression.html" class="title">Shell正则表达式</a>
              </p>
              <p class="item-date">
                <time datetime="2022-01-16T14:13:05.000Z" itemprop="datePublished">2022-01-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20211009/install-linux-on-android-phone.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="如何在安卓手机上安装Linux发行版" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20211009/install-linux-on-android-phone.html" class="title">如何在安卓手机上安装Linux发行版</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-09T15:16:37.000Z" itemprop="datePublished">2021-10-09</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">1.</span> <span class="toc-text">虚拟环境</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-1%E3%80%90%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E3%80%91%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E6%9C%89%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%EF%BC%9F"><span class="toc-number">2.</span> <span class="toc-text">12.1【虚拟环境】为什么要有虚拟环境？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-2-%E3%80%90%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E3%80%91%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%9A%E4%BD%BF%E7%94%A8-virtualenv"><span class="toc-number">3.</span> <span class="toc-text">12.2 【虚拟环境】方案一：使用 virtualenv</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%AE%89%E8%A3%85virtualenv"><span class="toc-number">3.1.</span> <span class="toc-text">1. 安装virtualenv</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8-virtualenvwrapper"><span class="toc-number">3.2.</span> <span class="toc-text">2. 使用 virtualenvwrapper</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%AE%9E%E6%88%98%E6%BC%94%E7%A4%BA"><span class="toc-number">3.3.</span> <span class="toc-text">3. 实战演示</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-1-%E4%BA%A4%E4%BA%92%E5%BC%8F%E4%B8%AD"><span class="toc-number">3.3.1.</span> <span class="toc-text">3.1 交互式中</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-2-%E5%B7%A5%E7%A8%8B%E9%A1%B9%E7%9B%AE%E4%B8%AD"><span class="toc-number">3.3.2.</span> <span class="toc-text">3.2 工程项目中</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3-PyCharm%E4%B8%AD"><span class="toc-number">3.3.3.</span> <span class="toc-text">3.3 PyCharm中</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-3-%E3%80%90%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E3%80%91%E6%96%B9%E6%A1%88%E4%BA%8C%EF%BC%9A%E4%BD%BF%E7%94%A8-pipenv"><span class="toc-number">4.</span> <span class="toc-text">12.3 【虚拟环境】方案二：使用 pipenv</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%AE%89%E8%A3%85pipenv"><span class="toc-number">4.1.</span> <span class="toc-text">1. 安装pipenv</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%88%9B%E5%BB%BA%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">4.2.</span> <span class="toc-text">2. 创建虚拟环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E6%9F%A5%E8%AF%A2%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">4.3.</span> <span class="toc-text">3. 查询虚拟环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E6%93%8D%E4%BD%9C%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">4.4.</span> <span class="toc-text">4. 操作虚拟环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E5%8C%85%E7%AE%A1%E7%90%86"><span class="toc-number">4.5.</span> <span class="toc-text">5. 虚拟环境包管理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%85%B6%E4%BB%96%E5%91%BD%E4%BB%A4"><span class="toc-number">4.6.</span> <span class="toc-text">6. 其他命令</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-4-%E3%80%90%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E3%80%91%E6%96%B9%E6%A1%88%E4%B8%89%EF%BC%9A%E4%BD%BF%E7%94%A8-pipx"><span class="toc-number">5.</span> <span class="toc-text">12.4 【虚拟环境】方案三：使用 pipx</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF-pipx"><span class="toc-number">5.1.</span> <span class="toc-text">1. 什么是 pipx</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%AE%89%E8%A3%85%E4%BD%BF%E7%94%A8"><span class="toc-number">5.2.</span> <span class="toc-text">2. 安装使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E6%9F%A5%E7%9C%8B%E5%8C%85"><span class="toc-number">5.3.</span> <span class="toc-text">3. 查看包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%AE%89%E8%A3%85%E5%8C%85"><span class="toc-number">5.4.</span> <span class="toc-text">4. 安装包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E8%BF%90%E8%A1%8CAPP"><span class="toc-number">5.5.</span> <span class="toc-text">4. 运行APP</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%8D%87%E7%BA%A7%E5%8C%85"><span class="toc-number">5.6.</span> <span class="toc-text">5. 升级包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%8D%B8%E8%BD%BD%E5%8C%85"><span class="toc-number">5.7.</span> <span class="toc-text">6. 卸载包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E4%BD%BF%E7%94%A8-pip"><span class="toc-number">5.8.</span> <span class="toc-text">7. 使用 pip</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E5%85%B6%E4%BB%96"><span class="toc-number">5.9.</span> <span class="toc-text">8. 其他</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-pipx-vs-pip"><span class="toc-number">5.10.</span> <span class="toc-text">9. pipx vs pip</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E5%8F%82%E8%80%83%E6%96%87%E7%AB%A0"><span class="toc-number">5.11.</span> <span class="toc-text">10. 参考文章</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-5-%E3%80%90%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E3%80%91%E6%96%B9%E6%A1%88%E5%9B%9B%EF%BC%9A%E4%BD%BF%E7%94%A8-poetry"><span class="toc-number">6.</span> <span class="toc-text">12.5 【虚拟环境】方案四：使用 poetry</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%AE%89%E8%A3%85-poetry"><span class="toc-number">6.1.</span> <span class="toc-text">1. 安装 poetry</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE"><span class="toc-number">6.2.</span> <span class="toc-text">2. 创建项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%88%9B%E5%BB%BA%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">6.3.</span> <span class="toc-text">3. 创建虚拟环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E4%BD%BF%E7%94%A8%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">6.4.</span> <span class="toc-text">4. 使用虚拟环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%8C%85%E7%9A%84%E7%AE%A1%E7%90%86"><span class="toc-number">6.5.</span> <span class="toc-text">5. 包的管理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%B8%B8%E7%94%A8%E9%85%8D%E7%BD%AE"><span class="toc-number">6.6.</span> <span class="toc-text">6. 常用配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E5%8F%82%E8%80%83%E6%96%87%E7%AB%A0"><span class="toc-number">6.7.</span> <span class="toc-text">7. 参考文章</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-6-%E3%80%90%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E3%80%91%E6%96%B9%E6%A1%88%E4%BA%94%EF%BC%9A%E4%BD%BF%E7%94%A8-venv"><span class="toc-number">7.</span> <span class="toc-text">12.6 【虚拟环境】方案五：使用 venv</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%88%9B%E5%BB%BA%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">7.1.</span> <span class="toc-text">1. 创建虚拟环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E8%BF%9B%E5%85%A5%E5%88%9B%E5%BB%BA%E7%8E%AF%E5%A2%83"><span class="toc-number">7.2.</span> <span class="toc-text">2. 进入创建环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E9%80%80%E5%87%BA%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83"><span class="toc-number">7.3.</span> <span class="toc-text">3. 退出虚拟环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E6%80%BB%E7%BB%93%E4%B8%80%E4%B8%8B"><span class="toc-number">7.4.</span> <span class="toc-text">4. 总结一下</span></a></li></ol></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-python-virtual-environment" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      Python虚拟环境
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar"></i>
	<a href="/20210629/python-virtual-environment.html" class="article-date">
	  发布于 <time datetime="2021-06-28T23:54:48.000Z" itemprop="datePublished">2021-06-29</time>
	</a>
</span>
<span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/20210629/python-virtual-environment.html" class="article-date">
	  更新于 <time datetime="2021-07-08T00:04:25.000Z" itemprop="dateUpdated">2021-07-08</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/python/">python</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/tags/python/" rel="tag">python</a>
  </span>


        

	<span class="article-read hidden-xs">
    	<i class="icon icon-eye-fill" aria-hidden="true"></i>
    	<span id="/20210629/python-virtual-environment.html" class="leancloud_visitors"  data-flag-title="Python虚拟环境">
			<span class="leancloud-visitors-count">0</span>
		</span>
    </span>

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/20210629/python-virtual-environment.html#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 5.9k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 22(分)</span>
	

      </div>
      <div style="background-color:#D7BDE2;border:1px solid #D7BDE2;border-radius:10px;padding:5px">
          <b>温馨提示</b>：点击页面下方<i style="color:red" class="icon icon-anchor"></i>以展开或折叠目录
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <p>摘要：本文介绍Python中常用虚拟环境的用法。<span id="more"></span></p>
<blockquote>
<p><font size=5><b>文章说明</b></font><br><strong>文章作者：</strong><a href="https://hwame.top">鴻塵</a><br><strong>参考资料：</strong></p>
<ul>
<li><a target="_blank" rel="noopener" href="http://python.iswbm.com/en/latest/chapters/p12.html">Python中文指南第十二章：虚拟环境</a><ul>
<li><a target="_blank" rel="noopener" href="http://python.iswbm.com/en/latest/c12/c12_01.html">12.1 【虚拟环境】为什么要有虚拟环境？</a></li>
<li><a target="_blank" rel="noopener" href="http://python.iswbm.com/en/latest/c12/c12_02.html">12.2 【虚拟环境】方案一：使用 virtualenv</a></li>
<li><a target="_blank" rel="noopener" href="http://python.iswbm.com/en/latest/c12/c12_03.html">12.3 【虚拟环境】方案二：使用 pipenv</a></li>
<li><a target="_blank" rel="noopener" href="http://python.iswbm.com/en/latest/c12/c12_04.html">12.4 【虚拟环境】方案三：使用 pipx</a></li>
<li><a target="_blank" rel="noopener" href="http://python.iswbm.com/en/latest/c12/c12_05.html">12.5 【虚拟环境】方案四：使用 poetry</a></li>
</ul>
</li>
<li><a target="_blank" rel="noopener" href="https://docs.python.org/zh-cn/3/library/venv.html">Python标准库venv-创建虚拟环境</a></li>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/liudinglong/p/12538579.html">Python 虚拟环境的使用-virtualenv/virtualenvwrapper、pycharm使用</a></li>
<li><a target="_blank" rel="noopener" href="https://www.runoob.com/manual/pythontutorial3/docs/html/venv.html">Runoob Python tutorial-虚拟环境和包-pyvenv</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/godot06/article/details/81079064">Python为什么要使用虚拟环境-Python虚拟环境的安装和配置-virtualenv</a></li>
<li><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/60647332">知乎：最全的Python虚拟环境使用方法-virtualenv/conda/pipenv</a></li>
</ul>
<p><strong>文章链接：</strong><a href="https://hwame.top/20210629/python-virtual-environment.html">Python虚拟环境</a><br><strong>文章说明接：</strong>这片文章是复制的<a target="_blank" rel="noopener" href="http://python.iswbm.com/en/latest/chapters/p12.html">Python中文指南第十二章：虚拟环境</a>，后面再慢慢整理吧慢慢改吧。</p>
</blockquote>
<h2 id="虚拟环境"><a href="#虚拟环境" class="headerlink" title="虚拟环境"></a>虚拟环境</h2><p>所谓<a target="_blank" rel="noopener" href="https://docs.python.org/zh-cn/3/glossary.html#term-virtual-environment">虚拟环境（virtual environment）</a>，是指一种采用协作式隔离的运行时环境，允许 Python 用户和应用程序在安装和升级 Python 分发包时不会干扰到同一系统上运行的其他 Python 应用程序的行为。</p>
<p>使用虚拟环境有以下优点：</p>
<ul>
<li>使不同应用开发环境独立；</li>
<li>环境升级不影响其他应用，也不会影响全局的python环境；</li>
<li>可以防止系统中出现包管理混乱和版本的冲突；</li>
<li>不同环境中Python依赖包相互独立，互不干扰。</li>
</ul>
<p>管理Python版本和环境的工具有很多，常用的有以下几种：</p>
<ul>
<li><code>venv</code>：Python自带的模块，</li>
<li><code>virtualenv</code>：</li>
<li><code>virtualenvwrapper</code>：</li>
<li><code>pipenv</code>：</li>
<li><code>pyvenv</code>：</li>
</ul>
<h2 id="12-1【虚拟环境】为什么要有虚拟环境？"><a href="#12-1【虚拟环境】为什么要有虚拟环境？" class="headerlink" title="12.1【虚拟环境】为什么要有虚拟环境？"></a>12.1【虚拟环境】为什么要有虚拟环境？</h2><p>虚拟环境的意义，就如同虚拟机 一样，它可以实现不同环境中Python依赖包相互独立，互不干扰。</p>
<p>举个例子吧。</p>
<p>假设我们的电脑里有两个项目，他们都用到同一个第三方包，本来一切都顺利。但是由于某种原因，项目B由于某些原因要使用这个第三方包的一些新特性（新版本才有），而如果就这样贸然升级了，对项目A的影响我们无法评估，这个时候我们就特别需要有一种解决方案可以让项目A和B，处于两个不同的Python环境中。互不影响。</p>
<p>为了方便大家对虚拟环境有个认识，我列举了下其优点：</p>
<ul>
<li>使不同应用开发环境独立</li>
<li>环境升级不影响其他应用，也不会影响全局的python环境</li>
<li>可以防止系统中出现包管理混乱和版本的冲突</li>
</ul>
<p>市场上管理 Python 版本和环境的工具有很多，这里列举几个：</p>
<ul>
<li><code>p</code>：非常简单的交互式 python 版本管理工具。</li>
<li><code>pyenv</code>：简单的 Python 版本管理工具。</li>
<li><code>Vex</code>：可以在虚拟环境中执行命令。</li>
<li><code>virtualenv</code>：创建独立 Python 环境的工具。</li>
<li><code>virtualenvwrapper</code>：virtualenv 的一组扩展。</li>
</ul>
<p>工具很多，但个人认为最好用的，当属 <code>virtualenvwrapper</code>，推荐大家也使用。</p>
<h2 id="12-2-【虚拟环境】方案一：使用-virtualenv"><a href="#12-2-【虚拟环境】方案一：使用-virtualenv" class="headerlink" title="12.2 【虚拟环境】方案一：使用 virtualenv"></a>12.2 【虚拟环境】方案一：使用 virtualenv</h2><h3 id="1-安装virtualenv"><a href="#1-安装virtualenv" class="headerlink" title="1. 安装virtualenv"></a>1. 安装virtualenv</h3><p>由于 virtualenvwrapper 是 virtualenv 的一组扩展，所以如果要使用 virtualenvwrapper，就必须先安装 virtualenv。</p>
<p><strong>基本使用</strong></p>
<p>由于virtualenv创建虚拟环境是在当前环境下创建的。所以我们要准备一个专门存放虚拟环境的目录。（以下操作在Linux在完成，windows相对简单，请自行完成，有不明白的请微信与我联系。）</p>
<p><strong>创建</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 准备目录并进入</span></span><br><span class="line">$ <span class="built_in">mkdir</span> -p /home/wangbm/Envs</span><br><span class="line">$ <span class="built_in">cd</span> !$</span><br><span class="line"></span><br><span class="line"><span class="comment">## 创建虚拟环境（按默认的Python版本）</span></span><br><span class="line"><span class="comment">## 执行完，当前目录下会有一个my_env01的目录</span></span><br><span class="line">$ virtualenv my_env01</span><br><span class="line"></span><br><span class="line"><span class="comment">## 你也可以指定版本</span></span><br><span class="line">$ virtualenv -p /usr/bin/python2.7 my_env01</span><br><span class="line">$ virtualenv -p /usr/bin/python3.6 my_env02</span><br><span class="line"></span><br><span class="line"><span class="comment">## 你肯定觉得每次都要指定版本，相当麻烦吧？</span></span><br><span class="line"><span class="comment">## 在Linux下，你可以把这个选项写进入环境变量中</span></span><br><span class="line">$ <span class="built_in">echo</span> <span class="string">&quot;export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python2.7&quot;</span> &gt;&gt; ~/.bashrc</span><br></pre></td></tr></table></figure>
<p><strong>进入/退出</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">cd</span> /home/wangbm/Envs</span><br><span class="line"></span><br><span class="line"><span class="comment">## 进入</span></span><br><span class="line">$ <span class="built_in">source</span> my_env01/bin/activate</span><br><span class="line"></span><br><span class="line"><span class="comment">## 退出</span></span><br><span class="line">$ deactivate</span><br></pre></td></tr></table></figure>
<p><strong>删除</strong><br>删除虚拟环境，只需删除对应的文件夹就行了。并不会影响全局的Python和其他环境。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">cd</span> /home/wangbm/Envs</span><br><span class="line">$ <span class="built_in">rm</span> -rf my_env01</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意：<br>创建的虚拟环境，不会包含原生全局环境的第三方包，其会保证新建虚拟环境的干净。</p>
</blockquote>
<p>如果你需要和全局环境使用相同的第三方包。可以使用如下方法：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 导出依赖包</span></span><br><span class="line">$ pip freeze &gt; requirements.txt</span><br><span class="line"></span><br><span class="line"><span class="comment">## 安装依赖包</span></span><br><span class="line">$ pip install -r requirements.txt </span><br></pre></td></tr></table></figure>
<h3 id="2-使用-virtualenvwrapper"><a href="#2-使用-virtualenvwrapper" class="headerlink" title="2. 使用 virtualenvwrapper"></a>2. 使用 virtualenvwrapper</h3><p>virtualenv 虽然已经相当好用了，可是功能还是不够完善。</p>
<p>你可能也发现了，要进入虚拟环境，必须得牢记之前设置的虚拟环境目录，如果你每次按规矩来，都将环境安装在固定目录下也没啥事。但是很多情况下，人是会懒惰的，到时可能会有很多个虚拟环境散落在系统各处，你将有可能忘记它们的名字或者位置。</p>
<p>还有一点，virtualenv 切换环境需要两步，退出 -&gt; 进入。不够简便。</p>
<p>为了解决这两个问题，virtualenvwrapper就诞生了。</p>
<p><strong>安装</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 安装 - Linux</span></span><br><span class="line">pip install virtualenvwrapper</span><br><span class="line"></span><br><span class="line"><span class="comment">## 安装 - Windows</span></span><br><span class="line">pip install virtualenvwrapper-win</span><br></pre></td></tr></table></figure>
<p><strong>配置</strong><br>先find一下<code>virtualenvwrapper.sh</code>文件的位置</p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">find / <span class="literal">-name</span> virtualenvwrapper.sh</span><br><span class="line"><span class="comment">## /usr/bin/virtualenvwrapper.sh</span></span><br></pre></td></tr></table></figure>
<p>若是 windows 则使用everything 查找 virtualenvwrapper.bat 脚本</p>
<figure class="highlight livescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">D:<span class="string">\Program</span> Files (x86)<span class="string">\Python38-32\Scripts\virtualenvwrapper.bat</span></span><br></pre></td></tr></table></figure>
<p>在~/.bashrc 文件新增配置</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">export</span> <span class="attribute">WORKON_HOME</span>=<span class="variable">$HOME</span>/.virtualenvs</span><br><span class="line"><span class="built_in">export</span> <span class="attribute">PROJECT_HOME</span>=<span class="variable">$HOME</span>/workspace</span><br><span class="line"><span class="built_in">export</span> <span class="attribute">VIRTUALENVWRAPPER_SCRIPT</span>=/usr/bin/virtualenvwrapper.sh</span><br><span class="line">source /usr/bin/virtualenvwrapper.sh</span><br></pre></td></tr></table></figure>
<p>若是 windows 则新增环境变量：<code>WORKON_HOME</code></p>
<p><img src="http://image.iswbm.com/20200209161935.png" alt=""></p>
<p><strong>基本语法</strong>：</p>
<p>mkvirtualenv [-a project_path] [-i package] [-r requirements_file] [virtualenv options] ENVNAME</p>
<p><strong>常用方法</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 创建</span></span><br><span class="line">$ mkvirtualenv my_env01</span><br><span class="line"></span><br><span class="line"><span class="comment">## 进入</span></span><br><span class="line">$ workon my_env01</span><br><span class="line"></span><br><span class="line"><span class="comment">## 退出</span></span><br><span class="line">$ deactivate</span><br><span class="line"></span><br><span class="line"><span class="comment">## 列出所有的虚拟环境，两种方法</span></span><br><span class="line">$ workon</span><br><span class="line">$ lsvirtualenv</span><br><span class="line"></span><br><span class="line"><span class="comment">## 在虚拟环境内直接切换到其他环境</span></span><br><span class="line">$ workon my_env02</span><br><span class="line"></span><br><span class="line"><span class="comment">## 删除虚拟环境</span></span><br><span class="line">$ rmvirtualenv my_env01</span><br></pre></td></tr></table></figure>
<p><strong>其他命令</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 列出帮助文档</span></span><br><span class="line">$ virtualenvwrapper</span><br><span class="line"></span><br><span class="line"><span class="comment">## 拷贝虚拟环境</span></span><br><span class="line">$ cpvirtualenv ENVNAME [TARGETENVNAME]</span><br><span class="line"></span><br><span class="line"><span class="comment">## 在所有的虚拟环境上执行命令</span></span><br><span class="line">$ allvirtualenv pip install -U pip</span><br><span class="line"></span><br><span class="line"><span class="comment">## 删除当前环境的所有第三方包</span></span><br><span class="line">$ wipeenv</span><br><span class="line"></span><br><span class="line"><span class="comment">## 进入到当前虚拟环境的目录</span></span><br><span class="line">$ cdsitepackages</span><br><span class="line"></span><br><span class="line"><span class="comment">## 进入到当前虚拟环境的site-packages目录</span></span><br><span class="line">$ cdvirtualenv</span><br><span class="line"></span><br><span class="line"><span class="comment">## 显示 site-packages 目录中的内容</span></span><br><span class="line">$ lssitepackages</span><br></pre></td></tr></table></figure>
<p>更多内容，可查看 官方文档<br><a target="_blank" rel="noopener" href="https://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html">https://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html</a></p>
<h3 id="3-实战演示"><a href="#3-实战演示" class="headerlink" title="3. 实战演示"></a>3. 实战演示</h3><p>以上内容，是一份使用指南。接下来，一起来看看，如何在项目中使用虚拟环境。</p>
<p>如何使用在我们的开发中使用我们的虚拟环境呢</p>
<p>通常我们使用的场景有如下几种</p>
<ul>
<li>交互式中</li>
<li>PyCharm中</li>
<li>工程中</li>
</ul>
<p>接下来，我将一一展示。</p>
<h4 id="3-1-交互式中"><a href="#3-1-交互式中" class="headerlink" title="3.1 交互式中"></a>3.1 交互式中</h4><p>先对比下，全局环境和虚拟环境的区别，全局环境中有requests包，而虚拟环境中并未安装。<br>当我们敲入 <code>workon my_env01</code>，前面有<code>my_env01</code>的标识，说明我们已经处在虚拟环境中。后面所有的操作，都将在虚拟环境下执行。<br><img src="https://i.loli.net/2018/06/11/5b1e7d36ce8ad.png" alt=""></p>
<h4 id="3-2-工程项目中"><a href="#3-2-工程项目中" class="headerlink" title="3.2 工程项目中"></a>3.2 工程项目中</h4><p>我们的工程项目，都有一个入口文件，仔细观察，其首行可以指定Python解释器。</p>
<p>倘若我们要在虚拟环境中运行这个项目，只要更改这个文件头部即可。</p>
<p>现在我还是以，<code>import requests</code> 为例，来说明，是否是在虚拟环境下运行的，如果是，则和上面一样，会报错。</p>
<p>文件内容：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/root/.virtualenvs/my_env01/bin/python</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="built_in">print</span> <span class="string">&quot;ok&quot;</span></span><br></pre></td></tr></table></figure>
<p>运行前，注意添加执行权限。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">chmod</span> +x ming.py</span><br></pre></td></tr></table></figure>
<p>好了。来执行一下</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ ./ming.py</span><br></pre></td></tr></table></figure>
<p>发现和预期一样，真的报错了。说明我们指定的虚拟环境有效果。<br><img src="https://i.loli.net/2018/06/11/5b1e7f140be6a.png" alt=""></p>
<h4 id="3-3-PyCharm中"><a href="#3-3-PyCharm中" class="headerlink" title="3.3 PyCharm中"></a>3.3 PyCharm中</h4><p>点击 File - Settings - Project - Interpreter<br><img src="https://i.loli.net/2018/06/11/5b1e805c996c8.png" alt=""><br>点击小齿轮。如图点击添加，按提示添加一个虚拟环境。然后点 OK 就可以使用这个虚拟环境，之后的项目都会在这个虚拟环境下运行。<br><img src="https://i.loli.net/2018/06/11/5b1e812db603f.png" alt=""></p>
<p><img src="http://image.iswbm.com/20210606214719.png" alt=""></p>
<h2 id="12-3-【虚拟环境】方案二：使用-pipenv"><a href="#12-3-【虚拟环境】方案二：使用-pipenv" class="headerlink" title="12.3 【虚拟环境】方案二：使用 pipenv"></a>12.3 【虚拟环境】方案二：使用 pipenv</h2><p>以前一直使用pip+virtualenv+virtualwrapper管理模块和环境， 但是virtualwrapper在windows上使用不太方便，而且包和环境分开管理确实经常不记得哪个是哪个了。 </p>
<p>为什么 会推荐 pipenv 呢？</p>
<ul>
<li>它是 <code>virtualenv</code> 和 <code>pip</code> 的合体，可以合起来使用；</li>
<li>使用<code>Pipfile</code> 和 <code>Pipfile.lock</code>替代<code>requirements.txt</code></li>
<li>可以使用 <code>pipenv graph</code>很方便的看出包的依赖关系。</li>
<li>通过加载<code>.env</code>文件简化开发工作流程</li>
</ul>
<h3 id="1-安装pipenv"><a href="#1-安装pipenv" class="headerlink" title="1. 安装pipenv"></a>1. 安装pipenv</h3><p>如果你的电脑上没有安装 pipenv，可以使用如下方法安装</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># mac</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">brew install pipenv</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># windows</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pip install [--user] pipenv</span></span><br></pre></td></tr></table></figure>
<p>如果你的电脑是 windows 的。</p>
<p><img src="http://image.iswbm.com/Fk6WZ2xbqg2DM3AvnYCpsiKQ4xOn" alt=""></p>
<p>需要将如标示路径，加入到 环境变量 PATH 中。</p>
<p><img src="http://image.iswbm.com/FjuJ8yZsgjkzVuBRZHxK1ZnnzaEX" alt=""></p>
<p>然后需要重启一下，CMD 终端才能够刷新环境变量。</p>
<h3 id="2-创建虚拟环境"><a href="#2-创建虚拟环境" class="headerlink" title="2. 创建虚拟环境"></a>2. 创建虚拟环境</h3><p>DjangoWebBlog 是我们的项目目录，进入这个目录下创建虚拟环境</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash"><span class="built_in">mkdir</span> DjangoWebBlog &amp;&amp; <span class="built_in">cd</span> DjangoWebBlog</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 在当前目录下创建一个虚拟环境（默认的Python版本）</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv install</span></span><br></pre></td></tr></table></figure>
<p>你也可以指定版本创建</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv --two      <span class="comment"># 相当于 pipenv --python /usr/bin/python2</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv --three    <span class="comment"># 相当于 pipenv --python /usr/bin/python3</span></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv --python 3.7 <span class="comment"># 也可以指定具体的版本</span></span></span><br><span class="line">pipenv install --python 2</span><br></pre></td></tr></table></figure>
<p>这边以安装 python2 版本的虚拟环境为例说明。</p>
<p><img src="http://image.iswbm.com/20190612211330.png" alt=""></p>
<p>如果你原项目使用的是 requirements.txt 这个管理包的方式，这时候执行 <code>pipenv --tow</code> 创建一个虚拟环境后，会找到 requirements.txt ，并根据这里面的依赖包生成 Pipfile文件。</p>
<p><img src="http://image.iswbm.com/20190612213015.png" alt=""></p>
<h3 id="3-查询虚拟环境"><a href="#3-查询虚拟环境" class="headerlink" title="3. 查询虚拟环境"></a>3. 查询虚拟环境</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 返回项目的路径</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv --<span class="built_in">where</span></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 返回虚拟环境路径</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv --venv</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 返回该虚拟环境的解释器</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv --py</span></span><br></pre></td></tr></table></figure>
<p>演示如下：</p>
<p><img src="http://image.iswbm.com/20190612213950.png" alt=""></p>
<h3 id="4-操作虚拟环境"><a href="#4-操作虚拟环境" class="headerlink" title="4. 操作虚拟环境"></a>4. 操作虚拟环境</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 进入这个虚拟环境</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv shell</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 退出这个虚拟环境</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash"><span class="built_in">exit</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">deactivate</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 移除当前目录的虚拟环境</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv --<span class="built_in">rm</span></span></span><br></pre></td></tr></table></figure>
<p>执行 <code>pipenv shell</code> 就可以进入这个虚拟环境，在头部会有虚拟环境的标识名称。有这个标识，说明已经进入虚拟环境。</p>
<p><img src="http://image.iswbm.com/20190612211925.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 在当前虚拟环境中运行</span></span><br><span class="line">$ pipenv run python  <span class="comment"># 进入交互式,跟直接执行 python 一样</span></span><br><span class="line">$ pipenv run python 文件名 <span class="comment"># 运行文件</span></span><br><span class="line">$ pipenv run pip ...  <span class="comment"># 运行pip</span></span><br></pre></td></tr></table></figure>
<h3 id="5-虚拟环境包管理"><a href="#5-虚拟环境包管理" class="headerlink" title="5. 虚拟环境包管理"></a>5. 虚拟环境包管理</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 安装一个本地包（setup.py）到虚拟环境（Pipfile）</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv install -e .</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 安装、卸载模块</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv install requests</span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv uninstall requests</span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv uninstall --all   <span class="comment"># 卸载全部包</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv install -r path/to/requirements.txt</span> </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 安装所有依赖</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv install --dev</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 更新包</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv update <span class="comment"># 更新所有包</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv update --outdated <span class="comment"># 打印所有要更新的包</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv update &lt;包名&gt; <span class="comment"># 更新指定的包</span></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 将Pipfile和Pipfile.lock文件里面的包导出为requirements.txt文件</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv run pip freeze  <span class="comment"># 相当于pipenv run pip freeze &gt;requirements.txt</span></span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv lock -r &gt; requirements.txt</span> </span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv lock -r --dev <span class="comment"># 若只想导出开发用的包</span></span></span><br></pre></td></tr></table></figure>
<h3 id="6-其他命令"><a href="#6-其他命令" class="headerlink" title="6. 其他命令"></a>6. 其他命令</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 创建一个包含预发布的锁文件:</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv lock --pre</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 打印所有包的依赖关系图</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv graph</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 检查安全漏洞</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipenv check</span></span><br></pre></td></tr></table></figure>
<p>打印该虚拟环境下所有包的依赖关系图</p>
<p><img src="http://image.iswbm.com/20190614000336.png" alt=""></p>
<p>有的python第三方包旧版本会有安全漏洞，使用 pipenv check 可以检查安全漏洞。</p>
<p><img src="http://image.iswbm.com/20190612215924.png" alt=""></p>
<h2 id="12-4-【虚拟环境】方案三：使用-pipx"><a href="#12-4-【虚拟环境】方案三：使用-pipx" class="headerlink" title="12.4 【虚拟环境】方案三：使用 pipx"></a>12.4 【虚拟环境】方案三：使用 pipx</h2><h3 id="1-什么是-pipx"><a href="#1-什么是-pipx" class="headerlink" title="1. 什么是 pipx"></a>1. 什么是 pipx</h3><p>pipx 是一款用于帮助你安装和运行那些用 python 编写的终端程序，它类似于 macOS 上的 brew，Ubuntu 上的 apt，CentOS 上的 yum。</p>
<p>pipx 依赖 pip 和 venv，它只能在 python 3.6+ 的 Python 版本中才能使用。</p>
<p>默认情况下，pipx 和 pip 一样会从 pypi 上安装包，同时 pipx 也能像 pip 一样从本地、git仓库、wheel 文件中安装包。</p>
<p>为了避免你在安装 python app时，由于多版本而导致冲突，通常我们会使用 venv 或者 virtualenv 新建一个虚拟环境，然后将 app 安装到虚拟环境中。</p>
<p>后续你对这个 app 的管理操作，都得先进入这个虚拟环境。</p>
<p>发现没有？好像有点麻烦。</p>
<p>pipx 的存在使这个流程变得更加舒畅，使用 pipx 你可以无需关注虚拟环境的存在，并在你的机器上安装多个版本的 python app。</p>
<h3 id="2-安装使用"><a href="#2-安装使用" class="headerlink" title="2. 安装使用"></a>2. 安装使用</h3><p>安装 pipx</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">python3 -m pip install --user pipx</span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">python3 -m userpath append ~/.local/bin</span></span><br><span class="line">Success!</span><br></pre></td></tr></table></figure>
<p>使用 Pipx 需要注意两个路径</p>
<ol>
<li>二进制文件的保存位置：默认是 <code>~/.local/bin</code>，可使用环境变量 <code>PIPX_BIN_DIR</code> 进行更改，或者执行如下命令(<code>python3 -m userpath append $&#123;you_path&#125;</code>)</li>
<li>虚拟环境的保存位置：默认是 <code>~/.local/pipx</code>，可使用环境变量 <code>PIPX_HOME</code> 进行更改</li>
</ol>
<p>在我安装好 pipx ，准备使用的时候，发现全局找不到 pipx 这个命令。</p>
<p><img src="http://image.iswbm.com/image-20201130124107950.png" alt=""></p>
<p>按照如上图所示，难道使用全路径执行命令？</p>
<p><strong>不，怎么都觉得不太对劲。。</strong></p>
<p>想要解决这个问题，其实很简单，有两种方法（两种都可以，我演示使用的第一种方法）：</p>
<ol>
<li>添加个软链接指向刚刚那个全路径就好啦</li>
<li>将这个路径添加到 PATH 中 <code>/Users/MING/Library/Python/3.9/bin/</code></li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash"><span class="built_in">ln</span> -s /Users/MING//Library/Python/3.9/bin/pipx /usr/local/bin/pipx</span></span><br></pre></td></tr></table></figure>
<p>软链接建好后，就可以直接使用 <code>pipx</code> 的命令啦。</p>
<p><img src="http://image.iswbm.com/image-20201130124554404.png" alt=""></p>
<p>刚刚我使用 pipx 安装了 youtube-dl 后，其实并没有将这个 youtube-dl 安装到系统全局的 Python 环境中。</p>
<p>还记得最开始，我强调过两个非常重要的路径吗？</p>
<p>现在来看一下，这个路径下面都有哪些东西？</p>
<p><img src="http://image.iswbm.com/image-20201130125257203.png" alt=""></p>
<p>从截图上可以看出</p>
<ul>
<li>pipx 在 <code>~/.local/pipx/venvs</code> 目录下新建了个名叫 <code>youtube-dl</code> 的虚拟机环境</li>
<li>并将 <code>youtube-dl</code> 安装到这个虚拟机环境中</li>
<li>然后在 <code>~/.local/bin</code> 的目录下新建一个软链接，指向这个虚拟环境中</li>
<li>这样 <code>youtube-dl</code> 就变成全局的工具啦。</li>
</ul>
<p><img src="http://image.iswbm.com/image-20201130131138939.png" alt=""></p>
<p>为了避免你新安装的 youtube-dl 与全局的冲突，你也可以指定 pipx 的命令来运行 youtube-dl </p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run youtube-dl --no-check-certificate https://www.bilibili.com/video/BV1jK4y1h7uA</span></span><br></pre></td></tr></table></figure>
<p>运行效果如下：</p>
<p><img src="http://image.iswbm.com/image-20201130210539907.png" alt=""></p>
<p>pip run 也可以直接执行在线的 python 脚本</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run https://gist.githubusercontent.com/cs01/fa721a17a326e551ede048c5088f9e0f/raw/6bdfbb6e9c1132b1c38fdd2f195d4a24c540c324/pipx-demo.py</span></span><br><span class="line">pipx is working!</span><br></pre></td></tr></table></figure>
<h3 id="3-查看包"><a href="#3-查看包" class="headerlink" title="3. 查看包"></a>3. 查看包</h3><p>查看已安装过的包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx list</span></span><br></pre></td></tr></table></figure>
<h3 id="4-安装包"><a href="#4-安装包" class="headerlink" title="4. 安装包"></a>4. 安装包</h3><p>下载最新版本的 python 包，并安装到新建的虚拟环境中</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx install &lt;PACKAGE&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="4-运行APP"><a href="#4-运行APP" class="headerlink" title="4. 运行APP"></a>4. 运行APP</h3><p><code>pipx run</code> 后面可接一个包的 url 链接，会将这个包下载下来并运行，也可以接已安装过的应用名来直接运行它</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run &lt;PACKAGE_URL/APP&gt;</span></span><br></pre></td></tr></table></figure>
<p>如果一个 app 有多个版本，那么可以通过 <code>spec</code> 指定版本号</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run --spec PACKAGE==1.0.0 app</span></span><br></pre></td></tr></table></figure>
<p>更神奇的是，pipx 支持指定 git 代码仓库直接运行</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run --spec git+https://github.com/psf/black.git black</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 指定分支</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run --spec git+https://github.com/psf/black.git@branch black</span>  </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 指定某个git hash</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run --spec git+https://github.com/psf/black.git@ce14fa8b497bae2b50ec48b3bd7022573a59cdb1 black</span> </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 指定某个发行版本</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx run --spec https://github.com/psf/black/archive/18.9b0.zip black <span class="comment"># install a release</span></span></span><br></pre></td></tr></table></figure>
<h3 id="5-升级包"><a href="#5-升级包" class="headerlink" title="5. 升级包"></a>5. 升级包</h3><p>升级某个包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx upgrade &lt;pkg&gt;</span></span><br></pre></td></tr></table></figure>
<p>升级全部包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx upgrade-all</span></span><br></pre></td></tr></table></figure>
<h3 id="6-卸载包"><a href="#6-卸载包" class="headerlink" title="6. 卸载包"></a>6. 卸载包</h3><p>卸载某个包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx uninstall &lt;pkg&gt;</span></span><br></pre></td></tr></table></figure>
<p>卸载全部包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx uninstall-all</span></span><br></pre></td></tr></table></figure>
<p>重装全部包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx reinstall-all</span></span><br></pre></td></tr></table></figure>
<h3 id="7-使用-pip"><a href="#7-使用-pip" class="headerlink" title="7. 使用 pip"></a>7. 使用 pip</h3><p>每执行一次 pipx install 就会新建一个虚拟环境，那我们有没有办法管理这些虚拟机环境呢？</p>
<p>比如我想看这个虚拟环境里安装了哪些包？</p>
<p>使用如下命令就可以像使用 pip 一样，来管理 pipx 的虚拟环境</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pipx runpip &lt;env_name&gt; &lt;args&gt;</span></span><br></pre></td></tr></table></figure>
<p>效果如下</p>
<p><img src="http://image.iswbm.com/image-20201130215320069.png" alt=""></p>
<h3 id="8-其他"><a href="#8-其他" class="headerlink" title="8. 其他"></a>8. 其他</h3><p>执行 <code>pipx completions</code> 可以启用 pipx 的补全说明。</p>
<p>对于不同的终端开启方式不一样，我使用的是 zsh，方法是</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash"><span class="built_in">autoload</span> -U bashcompinit</span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">bashcompinit</span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash"><span class="built_in">eval</span> <span class="string">&quot;<span class="subst">$(register-python-argcomplete pipx)</span>&quot;</span></span></span><br></pre></td></tr></table></figure>
<p>我安装好后，可以使用 tab 键进行命令补全。</p>
<p><img src="http://image.iswbm.com/image-20201130220233001.png" alt=""></p>
<p>执行 <code>pipx ensurepath</code> 可以确保 <code>~/.local/bin</code> 这个重要的目录，已经放入到 <code>$PATH</code> 的变量中。</p>
<p><img src="http://image.iswbm.com/image-20201130215826513.png" alt=""></p>
<h3 id="9-pipx-vs-pip"><a href="#9-pipx-vs-pip" class="headerlink" title="9. pipx vs pip"></a>9. pipx vs pip</h3><p>pipx 只是解决 pip 的一个痛点，因此他的适用场景比较单一，它只适用于安装和运行那些有提供命令行入口的app。</p>
<ul>
<li>pip 适用于大多数的 Python 版本，而 pipx 需要 Python 3.6+ 才可以使用</li>
<li>pipx 依赖 pip 和 venv，可以使用 pip 安装pipx ，反过来则不行。</li>
<li>pip 和 pipx 默认都是从 pypi 上安装包</li>
<li>pipx 在安装和管理 cli 应用程序时，比 pip 更灵活，它可以在允许在隔离环境中安装和运行 Python 应用</li>
</ul>
<h3 id="10-参考文章"><a href="#10-参考文章" class="headerlink" title="10. 参考文章"></a>10. 参考文章</h3><ul>
<li><a target="_blank" rel="noopener" href="https://github.com/pipxproject/pipx">https://github.com/pipxproject/pipx</a></li>
<li><a target="_blank" rel="noopener" href="https://pipxproject.github.io/pipx/comparisons/">https://pipxproject.github.io/pipx/comparisons/</a></li>
</ul>
<h2 id="12-5-【虚拟环境】方案四：使用-poetry"><a href="#12-5-【虚拟环境】方案四：使用-poetry" class="headerlink" title="12.5 【虚拟环境】方案四：使用 poetry"></a>12.5 【虚拟环境】方案四：使用 poetry</h2><h3 id="1-安装-poetry"><a href="#1-安装-poetry" class="headerlink" title="1. 安装 poetry"></a>1. 安装 poetry</h3><p>poetry提供多种安装方式，个人推荐从以下2种方式中选择：</p>
<p>方式一：（推荐）使用在线脚本进行安装，是最为推荐的安装方式</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python</span></span><br></pre></td></tr></table></figure>
<p>方式二：（pip） 官方不建议这么做，因为有可能会造成依赖冲突，可以考虑用 pipx 或 pipsi</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">pip install --user poetry</span></span><br></pre></td></tr></table></figure>
<p>安装后，可以使用如下命令检测是否可用</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry --version</span></span><br><span class="line">Poetry version 1.1.4</span><br></pre></td></tr></table></figure>
<h3 id="2-创建项目"><a href="#2-创建项目" class="headerlink" title="2. 创建项目"></a>2. 创建项目</h3><p>如果你是在一个已有的项目里使用 Poetry，你只需要执行 poetry init 命令来创建一个 pyproject.toml 文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry init</span></span><br></pre></td></tr></table></figure>
<p>而如果是新建 一个项目，可以使用这个命令</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry new demo-priject</span></span><br></pre></td></tr></table></figure>
<p>运行完后，在当前目录下就会多一个 <code>demo-project</code> 的目录，这个目录下的文件结构如下</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">tree demo-priject</span></span><br><span class="line">demo-priject</span><br><span class="line">├── README.rst</span><br><span class="line">├── demo_priject</span><br><span class="line">│   └── __init__.py</span><br><span class="line">├── pyproject.toml</span><br><span class="line">└── tests</span><br><span class="line">    ├── __init__.py</span><br><span class="line">    └── test_demo_priject.py</span><br></pre></td></tr></table></figure>
<p>如果要把项目代码放入到 src 目录下，在创建项目时，可以加上 <code>--src</code> 参数。</p>
<h3 id="3-创建虚拟环境"><a href="#3-创建虚拟环境" class="headerlink" title="3. 创建虚拟环境"></a>3. 创建虚拟环境</h3><p>使用 poetry install 命令创建虚拟环境（确保当前目录有 pyproject.toml 文件）：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry install</span></span><br></pre></td></tr></table></figure>
<p>这个命令会读取 pyproject.toml 中的所有依赖（包括开发依赖）并安装，如果不想安装开发依赖，可以附加 —no-dev 选项。如果项目根目录有 poetry.lock 文件，会安装这个文件中列出的锁定版本的依赖。如果执行 add/remove 命令的时候没有检测到虚拟环境，也会为当前目录自动创建虚拟环境。</p>
<p><img src="http://image.iswbm.com/image-20201220164337699.png" alt=""></p>
<h3 id="4-使用虚拟环境"><a href="#4-使用虚拟环境" class="headerlink" title="4. 使用虚拟环境"></a>4. 使用虚拟环境</h3><p>创建虚拟环境后，如果想要在虚拟环境下执行命令，比如去执行脚本，去使用 pip list 等等。</p>
<p>可以在项目目录下，使用如下命令</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry run &lt;commands&gt;</span></span><br></pre></td></tr></table></figure>
<p>比如我查看该虚拟环境中安装了哪些包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry run pip list</span></span><br></pre></td></tr></table></figure>
<p>再比如我想在该虚拟环境下执行 <code>app.py</code></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry run python app.py</span></span><br></pre></td></tr></table></figure>
<p>每次在虚拟环境下做点啥事，命令前面都要加上 <code>poetry run</code>，有点太麻烦了。</p>
<p>这时可以使用下面这条命令，直接激活当前的虚拟环境</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry shell</span></span><br></pre></td></tr></table></figure>
<h3 id="5-包的管理"><a href="#5-包的管理" class="headerlink" title="5. 包的管理"></a>5. 包的管理</h3><p>安装包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry add &lt;pkg&gt;</span></span><br></pre></td></tr></table></figure>
<p>添加 —dev 参数可以指定为开发依赖</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry add pytest --dev</span></span><br></pre></td></tr></table></figure>
<p>查看所有安装的依赖包</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry show</span></span><br></pre></td></tr></table></figure>
<p>加上 <code>--tree</code> 可以查看他们的依赖关系</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry show --tree</span></span><br></pre></td></tr></table></figure>
<p>加上 <code>--outdated</code> 可以查看可以更新的依赖</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry show --outdated</span></span><br></pre></td></tr></table></figure>
<p>如果要更新依赖可以执行这个命令</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 更新全部</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry update</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 更新某个依赖</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry update foo</span></span><br></pre></td></tr></table></figure>
<p>想卸载某个包，用这个命令</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry remove foo</span></span><br></pre></td></tr></table></figure>
<h3 id="6-常用配置"><a href="#6-常用配置" class="headerlink" title="6. 常用配置"></a>6. 常用配置</h3><p>Poetry 的配置存储在单独的文件中，比 Pipenv 设置环境变量的方式要方便一点。配置通过 poetry config 命令设置，比如下面的命令可以写入 PyPI 的账号密码信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry config http-basic.pypi username password</span></span><br></pre></td></tr></table></figure>
<p>下面的命令设置在项目内创建虚拟环境文件夹：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">poetry config settings.virtualenvs.in-project <span class="literal">true</span></span></span><br></pre></td></tr></table></figure>
<p>另一个常用的配置是设置 PyPI 镜像源，以使用豆瓣提供的 PyPI 镜像源为例，你需要在 pyproject.toml 文件里加入这部分内容：</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">[[tool.poetry.source]]</span></span><br><span class="line"><span class="attr">name</span> = <span class="string">&quot;douban&quot;</span></span><br><span class="line"><span class="attr">url</span> = <span class="string">&quot;https://pypi.doubanio.com/simple/&quot;</span></span><br></pre></td></tr></table></figure>
<p>不过经过测试 Poetry 会使用 pip.ini 设置的 PyPI 镜像，而且豆瓣的源好像很久没更新了（创建虚拟环境安装的默认依赖里 importlib-metadata==0.20 找不到），<a href="https://link.zhihu.com/?target=http%3A//greyli.com/set-custom-pypi-mirror-url-for-pip-pipenv-poetry-and-flit/">这篇文章</a>列出了一些其他国内的 PyPI 源。</p>
<h3 id="7-参考文章"><a href="#7-参考文章" class="headerlink" title="7. 参考文章"></a>7. 参考文章</h3><ul>
<li><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/81025311">相比 Pipenv，Poetry 是一个更好的选择</a></li>
</ul>
<h2 id="12-6-【虚拟环境】方案五：使用-venv"><a href="#12-6-【虚拟环境】方案五：使用-venv" class="headerlink" title="12.6 【虚拟环境】方案五：使用 venv"></a>12.6 【虚拟环境】方案五：使用 venv</h2><p>在前面介绍的几种方法中，都需要借助第三方模块来完成虚拟环境的管理。</p>
<p>但其实在 Python 3 中就自带了一个专门用门管理虚拟环境的模块，它叫 <code>venv</code>。</p>
<h3 id="1-创建虚拟环境"><a href="#1-创建虚拟环境" class="headerlink" title="1. 创建虚拟环境"></a>1. 创建虚拟环境</h3><p><code>venv</code> 后可以接一个目录（如果此目录不存在，会自动创建）用于创建你的虚拟环境，他可以是绝对路径，也可以是相对路径。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># mac or linux</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">python3 -m venv [venv_dir]</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># windows: 一定要指定  --without-pip</span></span> </span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 最后再手动执行命令安装 python -m ensurepip</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">python3 -m venv --without-pip [venv_dir]</span></span><br></pre></td></tr></table></figure>
<p>使用 venv 创建虚拟环境的速度非常快，大概只需要两三秒的样子。</p>
<p><img src="http://image.iswbm.com/image-20201226172542169.png" alt=""></p>
<p>创建完成后，在你所指定的目录下会有一个 <code>pyvenv.cfg</code> 的配置文件，它记录着虚拟环境的基本信息，包括你使用的 Python 的家目录，还有当前虚拟环境的 Python 版本，是否开启使用系统的 site-packages 模块，如果开启了，那么当你就可以直接使用系统中已经装过的第三方模块，但是你在虚拟环境下装的模块就不能被其他地方的程序使用。</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">home</span> = /usr/local/bin</span><br><span class="line"><span class="attr">include-system-site-packages</span> = <span class="literal">false</span></span><br><span class="line"><span class="attr">version</span> = <span class="number">3.9</span>.<span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>如果你的环境中有 Python 3.8 也有 Python 3.9 ，那该怎么办呢？</p>
<p>只要你在创建时，用你预期版本的 Python 去执行就好啦</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">python3.8 -m venv [venv_dir]</span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">python3.9 -m venv [venv_dir]</span></span><br></pre></td></tr></table></figure>
<p>可如果你的环境中有两个 Python 3.9 呢？你想使用不在 <code>PATH</code> 的中的 Python 去创建，就要用绝对路径去创建了。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">/usr/local/bin/python3 -m venv [venv_dir]</span></span><br></pre></td></tr></table></figure>
<h3 id="2-进入创建环境"><a href="#2-进入创建环境" class="headerlink" title="2. 进入创建环境"></a>2. 进入创建环境</h3><p>进入虚拟环境的方法，对比之前介绍的方案，venv 的方法就相当原始了。</p>
<p>如果你使用 Windows ，那么在 cmd 下进行 <code>Scripts</code> 目录，执行 <code>activate.bat</code></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># cmd.exe</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">.\Scripts\activate.bat</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># PowserShell</span></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">.\Scripts\Activate.ps1</span></span><br></pre></td></tr></table></figure>
<p>如果你使用PowserShell激活虚拟环境出现如下错误，那要先执行这个命令：<code>Set-ExecutionPolicy RemoteSigned</code>，再按 <code>Y</code></p>
<p><img src="http://image.iswbm.com/20201231140727.png" alt=""></p>
<p>而如果你使用的 Mac 或者 Linux，那么直接执行下面命令就行</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash"><span class="built_in">source</span> bin/activate</span></span><br></pre></td></tr></table></figure>
<p>执行完后，若在你的命令行下有 <code>demo</code> 字样（之所以是 demo ，因为我们创建时的目录名就是 demo），说明你已经处于虚拟环境下。 由于虚拟环境是全新的干净环境，此时你使用 <code>pip list</code> ，会看到啥包都没有，只有最基本的 pip 和 setuptools 。</p>
<p><img src="http://image.iswbm.com/image-20201226174305992.png" alt=""></p>
<h3 id="3-退出虚拟环境"><a href="#3-退出虚拟环境" class="headerlink" title="3. 退出虚拟环境"></a>3. 退出虚拟环境</h3><p>退出虚拟环境，无论是 Windows 、 Mac 、 还是 Linux ，方法都是同一条命令。退出后，你的虚拟环境名称（如上面的 <code>demo</code> ）也会消失。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">deactivate</span></span><br></pre></td></tr></table></figure>
<h3 id="4-总结一下"><a href="#4-总结一下" class="headerlink" title="4. 总结一下"></a>4. 总结一下</h3><p><code>venv</code> 是 Python3 中自带的虚拟环境管理工具，不需要额外安装，功能简单，用法也简单。但是它不能像 poetry 和 pipenv 用于项目的管理，因此 venv 建议只做了解，在一些简单的场景中可以使用，如果是复杂的项目中，可以直接上 poetry 和 pipenv。</p>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-license">
      <strong>文章作者： </strong><a href="https://hwame.top" style="color:#E541E5;"> 鴻塵</a>
    </li>
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://hwame.top/20210629/python-virtual-environment.html" title="Python虚拟环境" target="_blank" rel="external" style="color:#E541E5;">https://hwame.top/20210629/python-virtual-environment.html</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用《<a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external" style="color:#E541E5;"><u>CC BY 4.0 CN协议</u></a>》许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://hwame.top" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://hwame.top" target="_blank"><span class="text-dark">鴻塵</span><small class="ml-1x">Pythoner, Data Analyst</small></a></h3>
        <div>个人简介：处女座不适合做码农。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/20210716/mongodb-crud-operations.html" title="MongoDB增删改查"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/20210618/ansi-color-in-windows-cmd.html" title="Windows命令行中正确显示颜色"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span style="color:#C71585">[&nbsp;</span><span style="color:#C71585">文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span style="color:#C71585">]</span>
      </a>
    </li>
    
  </ul>
  
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,wechat,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  


</main>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2025 鴻塵
        
        
        <div class="publishby" style="font-family:Courier">
            <span id="busuanzi_container_site_pv">
                <i class="icon icon-eye"></i><span id="busuanzi_value_site_pv" style="font-family:Courier"></span>&nbsp;
                <i class="icon icon-users"></i><span id="busuanzi_value_site_uv" style="font-family:Courier"></span>
            </span>
            <!--
            <br>✯<a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/" style="color:#0FFFAA">鄂ICP备2020019329号</a>
            -->
            <br><i class="icon icon-clock" style="transform:rotate(90deg)"></i><span id="sitetime" style="font-family:Courier"></span>
        </div>
        
        <!--
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
        -->
    </div>
    
</footer>
<script>
    function siteTime(){
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth()+1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2020,05,19,21,20,52); //建站时间
        var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
        var diff = t2-t1;
        var diffYears = Math.floor(diff/years);
        var diffDays = Math.floor((diff/days)-diffYears*365);
        var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
        var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
        var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
        // 将「数字」转「补零字符串」
        var y = diffYears.toString()
        var d = diffDays.toString().padStart(3, '0')
        var h = diffHours.toString().padStart(2, '0')
        var m = diffMinutes.toString().padStart(2, '0')
        var s = diffSeconds.toString().padStart(2, '0')
        document.getElementById("sitetime").innerHTML=y+":"+d+":"+h+":"+m+":"+s;
    }
    siteTime();
</script>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<div id="go-top"></div>
<style type="text/css">
#go-top {
 width:40px;height:40px;
 background-color:#DDA0DD;
 position:relative;
 border-radius:20px;
 position:fixed;right:20px;bottom:50px;
 cursor:pointer;display:none;
}
#go-top:after {
 content:" ";
 position:absolute;left:14px;top:14px;
 border-top:2px solid #fff;border-right:2px solid #fff;
 width:12px;height:12px;
 transform:rotate(-45deg);
}
#go-top:hover {
 background-color:#8A2BE2;
}
</style>
<script>
$(function () {
  var top=$("#go-top");
  $(window).scroll(function () {
    ($(window).scrollTop() > 300) ? top.show(300) : top.hide(200);
    $("#go-top").click(function () {
      $('body,html').animate({scrollTop:0});
      return false();
    })
  });
});
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>





   




   
    

  <script src='/waline.js'></script>
  <link rel="stylesheet" type="text/css" href="/waline.css" />
  
  <script type="text/javascript">
 
  
Waline.init({
      el: '#vcomments',
      serverURL: 'https://waline.hwame.top',
});
  </script>

     


<!-- 20201211添加判断 -->

   
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script>
  <script>
  //利用 FancyBox 实现点击图片放大
  $(document).ready(function() {
    $('article img').not('[hidden]').not('.panel-body img').each(function() {
      var $image = $(this);
      var imageCaption = $image.attr('alt');
      var $imageWrapLink = $image.parent('a');
      if ($imageWrapLink.length < 1) {
        var src = this.getAttribute('src');
        var idx = src.lastIndexOf('?');
        if (idx != -1) {
          src = src.substring(0, idx);
        }
        $imageWrapLink = $image.wrap('<a href="' + src + '"></a>').parent('a');
      }
      $imageWrapLink.attr('data-fancybox', 'images');
      if (imageCaption) {
        $imageWrapLink.attr('data-caption', imageCaption);
      }
    });
    $().fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: true,
    });
  });
  </script>







  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
      z-index: 2;
    }

    .highlight-wrap:hover .copy-btn,
        .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    addLoadEvent(()=>{
      $('.highlight').each(function (i, e) {
        var $wrap = $('<div>').addClass('highlight-wrap')
        $(e).after($wrap)
        $wrap.append($('<button>').addClass('copy-btn').append('一键复制').on('click', function (e) {
          var code = $(this).parent().find(".code")[0].innerText
          
          var ta = document.createElement('textarea')
          document.body.appendChild(ta)
          ta.style.position = 'absolute'
          ta.style.top = '0px'
          ta.style.left = '0px'
          ta.value = code
          ta.select()
          ta.focus()
          var result = document.execCommand('copy')
          document.body.removeChild(ta)
          
            if(result)$(this).text('复制成功')
            else $(this).text('复制失败')
          
          $(this).blur()
        })).on('mouseleave', function (e) {
          var $b = $(this).find('.copy-btn')
          setTimeout(function () {
            $b.text('一键复制')
          }, 300)
        }).append(e)
      })
    })
  </script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>